import {
    Controller,
    Get,
    Post,
    HttpCode,
    Header,
    Redirect,
    Query,
    Param,
    Body,
    HttpStatus,
    HttpException,
    UseFilters,
    ForbiddenException,
    UsePipes,
    UseGuards,
    UseInterceptors,
} from '@nestjs/common';
import { CatsService } from './cats.service';
import { Cat } from './interfaces/cat.interface';
import { HttpExceptionFilter } from '../filters/http-exception.filter';
import { ApiTags } from '@nestjs/swagger';
import { CreateCatDto } from './create-cat.dto';
import { ValidationPipe } from '../pipes/validate.pipe';
import { ParseIntPipe } from '../pipes/parse-int.pipe';
import { AuthGuard } from '../auth.guard';
import { Roles } from '../decorator/roles.decorator';
import { LoggingInterceptor } from '../interceptor/logging.interceptor';

@Controller('cats')
@ApiTags('cats')
@UseInterceptors(LoggingInterceptor)
export class CatsController {
    constructor(private catService: CatsService) {}

    @HttpCode(200)
    @Post('name*')
    @Header('Cache-Control', 'none')
    create(): string {
        return 'success create cat';
    }

    @Get()
    async findAll(): Promise<Cat[]> {
        return this.catService.findAll();
    }

    @Post()
    @UseGuards(AuthGuard)
    @UsePipes(ValidationPipe)
    @Roles('admin', 'manager')
    async build(@Body() createCatDto: CreateCatDto) {
        this.catService.create(createCatDto);
        return 'ok';
    }

    @Get('docs')
    @Redirect('http://localhost:3000/cats', 302)
    getDocs(@Query('v') v) {
        console.log(v);
        if (v === 3) {
            // 当query参数v的值为3时，重定向到http://localhost:3000
            return {
                statusCode: 201,
                url: 'http://localhost:3000/cat/book',
            };
        }
    }

    @Get(':id')
    findOne(@Param('id', new ParseIntPipe()) id) {
        console.log(typeof id);
        return 'find ' + id;
    }

    @Get('book/:id')
    getBook(@Param() param): string {
        console.log(param.id);
        return 'I am a book ' + param.id;
    }

    @Get('error')
    async hrowError() {
    // throw new HttpException('Forbidden', HttpStatus.FORBIDDEN)
    // 自定义异常相应内容
        throw new HttpException(
            {
                statusCode: HttpStatus.FORBIDDEN,
                data: {},
                message: 'This is a message',
            },
            HttpStatus.FORBIDDEN,
        );
    }

    @Get('http-error')
    @UseFilters(new HttpExceptionFilter()) // 也可以放到control类上，进行整个control的错误过滤
    throwHttpError(@Body() data: CreateCatDto) {
        throw new ForbiddenException();
    }

    @Get('internal')
    throwInternal() {
    // 触发全局注册的过滤器
        throw new TypeError('type error');
    }
}
